using Microsoft.AspNetCore.Mvc;
using RAGApp.Api.Models.DTOs;
using RAGApp.Api.Services.Interfaces;

namespace RAGApp.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DocumentController : ControllerBase
{
    private readonly IDocumentService _documentService;
    private readonly ILogger<DocumentController> _logger;

    public DocumentController(IDocumentService documentService, ILogger<DocumentController> logger)
    {
        _documentService = documentService;
        _logger = logger;
    }

    [HttpPost]
    public async Task<ActionResult<DocumentResponseDto>> UploadDocument([FromBody] DocumentUploadDto dto)
    {
        try
        {
            var result = await _documentService.UploadDocumentAsync(dto);
            return Ok(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "上传文档时发生错误");
            return StatusCode(500, "上传文档时发生错误");
        }
    }

    [HttpGet]
    public async Task<ActionResult<List<DocumentResponseDto>>> GetAllDocuments()
    {
        try
        {
            var documents = await _documentService.GetAllDocumentsAsync();
            return Ok(documents);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文档列表时发生错误");
            return StatusCode(500, "获取文档列表时发生错误");
        }
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<DocumentResponseDto>> GetDocument(Guid id)
    {
        try
        {
            var document = await _documentService.GetDocumentByIdAsync(id);
            if (document == null)
                return NotFound();

            return Ok(document);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取文档时发生错误");
            return StatusCode(500, "获取文档时发生错误");
        }
    }

    [HttpDelete("{id}")]
    public async Task<ActionResult> DeleteDocument(Guid id)
    {
        try
        {
            var result = await _documentService.DeleteDocumentAsync(id);
            if (!result)
                return NotFound();

            return NoContent();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除文档时发生错误");
            return StatusCode(500, "删除文档时发生错误");
        }
    }
} 
 